package com.proscenic.oauth2.server.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.proscenic.oauth2.server.domain.User;
import com.proscenic.oauth2.server.mapper.UserMapper;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;

/**
 * 自义定登录验证
 * @version 1.0
 * created by chenxin on 2022/3/7 17:52
 */
@Service
public class LoginService implements UserDetailsService {
    @Resource
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if(ObjectUtils.isEmpty(username)){
            throw new UsernameNotFoundException("用户名不能为空");
        }

        User user = userMapper.selectOne(Wrappers.<User>query().lambda().eq(User::getUsername, username));
        if(user == null){
            throw new UsernameNotFoundException("用户不存在");
        }

        org.springframework.security.core.userdetails.UserDetails userDetails = org.springframework.security.core.userdetails.User.builder()
                .username(user.getUsername())
                .password(user.getPassword())
                .authorities("role")
                .build();
        return userDetails;
    }

    public static void main(String[] args) {
        String password = "123456";
        String encode = new BCryptPasswordEncoder().encode(password);
        System.out.println(encode);
    }
}
